package com.basic.library.utils;


import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.ActivityManager.RunningTaskInfo;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.Intent.ShortcutIconResource;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.TypedArray;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.telephony.PhoneNumberUtils;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.text.format.Time;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.basic.library.R;
import com.basic.library.base.BaseApplication;
import com.basic.library.utils.toast.ToastCompat;
import com.basic.library.view.ActionSheetDialog;
import com.github.promeg.pinyinhelper.Pinyin;

import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * 文 件 名 : CommonUtils
 * 创 建 人： gejian
 * 日     期：2013-11-4
 * 修 改 人：gejian
 * 日    期：2013-11-4
 * 描    述：常用的程序的方法类
 */
public class CommonUtils {

    private final static String TAG = CommonUtils.class.getName();
    public static String SETTING_NAME = TAG + "_SETTING_NAME";
    public static String CONTACTS_NAME = TAG + "_CONTACTS_NAME";

    //SharedPreferences的key
    public static final String SP_isInstallShortCut = "isInstallShortCut";  //是否添加桌面图标的key索引
    public static final String SP_isFirstOpenSoft = "isFirstOpenSoft";        //是否 首次加载应用的key索引
    public static final String SP_LastLogin = "LastLogin";                    //最近登录用户信息的key索引
    public static final String SP_COOKIES = "Cookies";                        //cookies的key索引
    public static String updateUrl;

    public static boolean isCellphone(String str) {
//		Pattern pattern = Pattern.compile("^(1[3|5|7|8|][0-9]{9})$");
        Pattern pattern = Pattern.compile("^(1[0-9][0-9]{9})$");
        Matcher matcher = pattern.matcher(str);
        if (matcher.matches()) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 判断是否已添加桌面图标
     */
    public static void checkShortCut() {
        boolean isInstallShortCut = PreferencesUtils.getBooleanPreferences(SETTING_NAME,
                SP_isInstallShortCut, false);
        // 存在快捷方式或者不允许添加，return
        if (isInstallShortCut)
            return;
        addShortcut();
        //保存配置
        PreferencesUtils.setBooleanPreferences(SETTING_NAME, SP_isInstallShortCut, true);
    }

    /**
     * 判断是否已添加桌面图标
     */
    public static boolean isFirstOpenSoft() {
        boolean isFirstOpenSoft = PreferencesUtils.getBooleanPreferences(SETTING_NAME,
                SP_isFirstOpenSoft, true);
        return isFirstOpenSoft;
    }

    /**
     * 添加桌面图标
     */
    public static void addShortcut() {
        Context c = BaseApplication.getInstance().getApplicationContext();
        Intent shortcut = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
        // 快捷方式的名称
        shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, c.getResources().getString(R.string.app_name_en));
        // 不允许重复创建
        shortcut.putExtra("duplicate", false);
        String action = "com.android.action.install";
        Intent respondIntent = new Intent(c, c.getClass());
        respondIntent.setAction(action);
        shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, respondIntent);
        // 快捷方式的图标
        ShortcutIconResource iconRes = ShortcutIconResource.fromContext(c, R.mipmap.ic_launcher);
        shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconRes);

        c.sendBroadcast(shortcut);
    }

    /**
     * 获取本地Ip
     *
     * @return
     */
    public static String getLocalIpAddress() {
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress()) {
                        return inetAddress.getHostAddress().toString();
                    }
                }
            }
        } catch (SocketException ex) {
        }
        return null;
    }

    public static boolean disposeSoapDataException(Object result) {
        boolean isReturn = false;
        if (!NetworkUtils.isNetworkAvailable()) {
            ToastCompat.show(BaseApplication.getInstance()
                    .getApplicationContext().getResources()
                    .getString(R.string.hint_NoNetwork));
            isReturn = true;
        } else if (NetworkUtils.isNetworkAvailable() && result == null) {
            ToastCompat.show(BaseApplication.getInstance()
                    .getApplicationContext().getResources()
                    .getString(R.string.hint_NetworkException));
            isReturn = true;
        }
        if (result != null) { //有网络，或用缓存
            isReturn = false;
        }
        return isReturn;
    }

    public static boolean disposeSoapDataException(Object result, String cachekey) {
        boolean isReturn = false;
        if (!NetworkUtils.isNetworkAvailable()) {
            ToastCompat.show(BaseApplication.getInstance()
                    .getApplicationContext().getResources()
                    .getString(R.string.hint_NoNetwork));
            isReturn = true;
        } else if (NetworkUtils.isNetworkAvailable() && result == null) {
            ToastCompat.show(BaseApplication.getInstance()
                    .getApplicationContext().getResources()
                    .getString(R.string.hint_NetworkException));
            isReturn = true;
        }
//		else if(result != null && result instanceof DataResult){
//			String flag;
//			String msg;
//			flag = ((DataResult)result).getResCode();
//			msg = ((DataResult)result).getMsg();
//			if(flag.equals(DataResult.RESULT_FAIL)){
//				if(BaseApplication.getInstance().getACache().getAsString(cachekey) != null){
//					BaseApplication.getInstance().getACache().remove(cachekey);
//				}
//			}
//		}
        return isReturn;
    }

    /*
     * // 验证邮箱的正则表达式
     */
    public static boolean checkEmail(String email) {
        // 验证邮箱的正则表达式 //电子邮件
        String check = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
        Pattern regex = Pattern.compile(check);
        Matcher matcher = regex.matcher(email);
        boolean isMatched = matcher.matches();
        return isMatched;
    }

    /*
     * 检验手机号码的合法性
     */
    public static boolean checkPhoneNo(String phoneNo) {
        Pattern p = Pattern.compile("^1[3|4|5|7|8|][0-9]{9}$");
        Matcher m = p.matcher(phoneNo);
        boolean isMatched = m.matches();
        return isMatched;
    }

    /*
     *验证身份证合法性
     */
    public static boolean checkIdentityNo(String identityNo) {
        Pattern p15 = Pattern.compile("^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$");
        Pattern p18 = Pattern.compile("^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}([0-9]|X)$");
        Matcher m15 = p15.matcher(identityNo);
        Matcher m18 = p18.matcher(identityNo);
        boolean isMatched = m15.matches() || m18.matches();
        return isMatched;
    }

    /*
     *验证身份证合法性
     */
    public static boolean checkIdentityNo(EditText et) {
        String identityNo = et.getText().toString().trim();
        Pattern p15 = Pattern.compile("^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$");
        Pattern p18 = Pattern.compile("^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}([0-9]|X)$");
        Matcher m15 = p15.matcher(identityNo);
        Matcher m18 = p18.matcher(identityNo);
        boolean isMatched = m15.matches() || m18.matches();
        if (isMatched == false) {
            ToastCompat.show("身份证格式不正确");
        }
        return isMatched;
    }

    /*
     * 检验字符串是否只有字母和数字
     */
    public static boolean checkStr(String str) {
        Pattern p = Pattern.compile("^[0-9a-zA-Z]*$");
        Matcher m = p.matcher(str);
        boolean isMatched = m.matches();
        return isMatched;
    }

    /**
     * 通过Service的类名来判断是否启动某个服务
     *
     * @param context
     * @param className
     * @return
     */
    public static boolean IsStartService(Context context, String className) {
        ActivityManager myManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        ArrayList<RunningServiceInfo> runningService = (ArrayList<RunningServiceInfo>) myManager.getRunningServices(30);
        for (int i = 0; i < runningService.size(); i++) {
            if (runningService.get(i).service.getClassName().toString().equals(className)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 判断指定包名的进程是否运行
     *
     * @param context
     * @param packageName 指定包名
     * @return 是否运行
     */
    public static boolean isRunningApp(Context context, String packageName) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<RunningTaskInfo> list = am.getRunningTasks(100);
        for (RunningTaskInfo info : list) {
            if (info.topActivity.getPackageName().equals(packageName) && info.baseActivity.getPackageName().equals(packageName)) {
                return true;
            }
        }
        return false;
    }

    public static void setListViewHeightBasedOnChildren(ListView listView) {
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            // pre-condition
            return;
        }

        int totalHeight = 0;
        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 2));

        listView.setLayoutParams(params);
    }

    public static boolean isActivityShowing(String className) {
        boolean result = false;
        ActivityManager am = (ActivityManager) BaseApplication.getInstance().getApplicationContext()
                .getSystemService(Context.ACTIVITY_SERVICE);
        ComponentName cn = am.getRunningTasks(2).get(0).topActivity;
        if (cn != null) {
            if (className.equals(cn.getClassName())) {
                result = true;
            }
        }
        return result;
    }

    //取两位小数
    public static String getDecimal(Double value) {
        if (value == null)
            value = 0.0;
        DecimalFormat df = new DecimalFormat("##0.00");
        return df.format(value);
    }

    public static String getDecimalInt(Double value) {
        if (value == null)
            value = 0.0;
        DecimalFormat df = new DecimalFormat("##0");
        return df.format(value);
    }

    public static String getDecimal(Double value, String type) {
        if (value == null)
            value = 0.0;
        DecimalFormat df = new DecimalFormat(type);
        return df.format(value);
    }

    /*
     * MD5加密（32位）
     */
    public static String toMD5(String str) {
        MessageDigest messageDigest = null;
        try {
            messageDigest = MessageDigest.getInstance("MD5");
            messageDigest.reset();
            messageDigest.update(str.getBytes("UTF-8"));
        } catch (NoSuchAlgorithmException e) {
            System.exit(-1);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        byte[] byteArray = messageDigest.digest();
        StringBuffer md5StrBuff = new StringBuffer();
        for (int i = 0; i < byteArray.length; i++) {
            if (Integer.toHexString(0xFF & byteArray[i]).length() == 1)
                md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i]));
            else
                md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
        }
        return md5StrBuff.toString();
        //16位   return md5StrBuff.toString().substring(8, 24);
    }

    //获取手机的IMIE号码
    public static String getImieNumber() {
        TelephonyManager tm = (TelephonyManager) BaseApplication.getInstance().getApplicationContext().getSystemService(Context.TELEPHONY_SERVICE);
        @SuppressLint("MissingPermission") String deviceId = tm.getDeviceId();
        return deviceId;
    }


    public static int getAndroidSDKVersion() {
        int version = 0;
        try {
            version = Integer.valueOf(Build.VERSION.SDK);
        } catch (NumberFormatException e) {

        }
        return version;
    }

    public static synchronized String getAppName(Context context) {
        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(
                    context.getPackageName(), 0);
            int labelRes = packageInfo.applicationInfo.labelRes;
            return context.getResources().getString(labelRes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 返回当前程序版本号
     */
    public static int getAppVersionCode(Context context) {
        int versionCode = -1;
        PackageManager pm = context.getApplicationContext().getPackageManager();
        PackageInfo pi = null;
        try {
            pi = pm.getPackageInfo(context.getApplicationContext().getPackageName(), 0);
            versionCode = pi.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionCode;
    }


    /**
     * 返回当前程序版本名
     */
    public static String getAppVersionName(Context context) {
        String versionName = "";
        try {
            PackageManager pm = context.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
            versionName = pi.versionName;
//            versioncode = pi.versionCode;
            if (versionName == null || versionName.length() <= 0) {
                return "";
            }
        } catch (Exception e) {
            Log.e("VersionInfo", "Exception", e);
        }
        return versionName;
    }

    //跳转到当前APP详情页面
    public static void getAppDetailSettingIntent(Context context) {
        Intent localIntent = new Intent();
        localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= 9) {
            localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
            localIntent.setData(Uri.fromParts("package", context.getPackageName(), null));
        } else if (Build.VERSION.SDK_INT <= 8) {
            localIntent.setAction(Intent.ACTION_VIEW);
            localIntent.setClassName("com.android.settings", "com.android.settings.InstalledAppDetails");
            localIntent.putExtra("com.android.settings.ApplicationPkgName", context.getPackageName());
        }
        context.startActivity(localIntent);
    }

    public static boolean checkPhone(String phone) {
        if (TextUtils.isEmpty(phone)) {
            ToastCompat.show("请输入手机号码");
            return false;
        }
        if (phone.length() != 11) {
            ToastCompat.show("手机号码格式不正确");
            return false;
        }
        return true;
    }

    public static boolean isNotEmpty(Context context, EditText et, String msgtype) {
        String s = et.getText().toString().trim();
        if (TextUtils.isEmpty(s)) {
            ToastCompat.show(msgtype);
            return false;
        }
        return true;
    }

    public static boolean isNotEmpty(Object s, String msgtype) {
        if (s == null) {
            ToastCompat.show(msgtype);
            return false;
        }
        if (s instanceof String) {
            String s1 = (String) s;
            if (TextUtils.isEmpty(s1)) {
                ToastCompat.show(msgtype);
                return false;
            }
        }
        return true;
    }

    public static boolean isNotEmpty(Context context, EditText et) {
        String s = et.getText().toString().trim();
        if (TextUtils.isEmpty(s)) {
            ToastCompat.show(et.getHint().toString());
            return false;
        }
        return true;
    }

    public static String getText(TextView tv) {
        return tv.getText().toString().trim();
    }

    //拨打电话
    public static void call(final String phone) {
//        new AlertDialog.Builder(context).setTitle("拨打电话")
//                .setMessage(phone)
//                .setPositiveButton("拨打", new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//                        try {
//                            Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + phone));
//                            context.startActivity(intent);
//                        } catch (Exception e) {
//                        }
//                    }
//                }).setNegativeButton("取消", null).show();
        Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phone));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        BaseApplication.getInstance().startActivity(intent);
    }

    //拨打电话
    public static void calls(final String phone) {
        ActionSheetDialog asd = new ActionSheetDialog(BaseApplication.getInstance().getActivityLast())
                .builder();
        for (String s : phone.split(",")) {
            asd.addSheetItem(s, ActionSheetDialog.SheetItemColor.Black, new ActionSheetDialog.OnSheetItemClickListener() {
                @Override
                public void onClick(int which) {
                    Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + s));
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    BaseApplication.getInstance().startActivity(intent);
                }
            });
        }
        asd.create().show();
    }

    /**
     * 调起系统发短信功能
     *
     * @param phoneNumber
     * @param message
     */
    public static void doSendSMSTo(String phoneNumber, String message) {
        if (PhoneNumberUtils.isGlobalPhoneNumber(phoneNumber)) {
            Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:" + phoneNumber));
            intent.putExtra("sms_body", message);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            BaseApplication.getInstance().startActivity(intent);
        }
    }

    /**
     * 复制到剪贴板
     *
     * @param content
     * @param label
     */
    public static void copyToClipboard(String content, String label) {
        if (label == null)
            label = System.currentTimeMillis() + "";
        //获取剪贴板管理器：
        ClipboardManager cm = (ClipboardManager) BaseApplication.getInstance().getSystemService(Context.CLIPBOARD_SERVICE);
        // 创建普通字符型ClipData
        ClipData mClipData = ClipData.newPlainText(label, content);
        // 将ClipData内容放到系统剪贴板里。
        cm.setPrimaryClip(mClipData);
    }

    /**
     * 是否网络连通，不管什么网络
     *
     * @param context
     * @return
     */
    public static boolean isNetworkConnected(Context context) {
        try {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mNetworkInfo = mConnectivityManager
                    .getActiveNetworkInfo();
            if (mNetworkInfo != null) {
                return mNetworkInfo.isConnected();
            } else {
                return false;
            }
        } catch (Exception e) {
            Log.e(TAG, "isNetworkConnected fail:" + e.toString());
            // LG，有时没有connectivity_service，抛IllegalArgumentException
            return false;
        }
    }

    public static int getAttrColor(Context context, int colorName) {
        int[] attrsArray = {colorName};
        TypedArray typedArray = context.obtainStyledAttributes(attrsArray);
        int accentColor = typedArray.getColor(0, 000000);
        typedArray.recycle();
        return accentColor;
    }

    //时间选择器获取时间格式
    public static String getTime(String s){
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat(s);
        return format.format(date);
    }

    //判断时间大小
    public static boolean timeCompare(String startTime, String endTime,String pattern){
        //注意：传过来的时间格式必须要和这里填入的时间格式相同
        SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
        try {
            Date date1 = dateFormat.parse(startTime);//开始时间
            Date date2 = dateFormat.parse(endTime);//结束时间
            // 结束时间小于等于开始时间
            if (date2.getTime() <= date1.getTime()){
                //结束时间小于开始时间
                return true;
            }
        } catch (Exception e) {

        }
        return false;
    }

    //将文字转为拼音
    public static String tinypinyin(String src) {
        char[] t1 = null;
        t1 = src.toCharArray();
        String t4 = "";
        int t0 = t1.length;
        for (int i = 0; i < t0; i++) {
            // 判断是否为汉字字符
            if (java.lang.Character.toString(t1[i]).matches(
                    "[\\u4E00-\\u9FA5]+")) {
                t4 += Pinyin.toPinyin(t1[i]);
            } else
                t4 += java.lang.Character.toString(t1[i]);
        }
        return t4;
    }
    public static String douToStr(Double d) {
        String  s = String.format(Locale.ENGLISH, "%.2f", d);
        return s;
    }

    /***
     *
     * @param beginHour 开始小时       比如   23
     * @param beginMin  开始小时的分钟  比如  00
     * @param endHour   结束小时        比如  5
     * @param endMin    结束小时的分钟   比如 00
     * @return         true表示范围内   否则false
     */
    public static boolean atTheCurrentTime(int beginHour, int beginMin, int endHour, int endMin) {
        boolean result = false;
        final long aDayInMillis = 1000 * 60 * 60 * 24;
        final long currentTimeMillis = System.currentTimeMillis();
        Time now = new Time();
        now.set(currentTimeMillis);
        Time startTime = new Time();
        startTime.set(currentTimeMillis);
        startTime.hour = beginHour;
        startTime.minute = beginMin;
        Time endTime = new Time();
        endTime.set(currentTimeMillis);
        endTime.hour = endHour;
        endTime.minute = endMin;
        /**跨天的特殊情况(比如23:00-2:00)*/
        if (!startTime.before(endTime)) {
            startTime.set(startTime.toMillis(true) - aDayInMillis);
            result = !now.before(startTime) && !now.after(endTime); // startTime <= now <= endTime
            Time startTimeInThisDay = new Time();
            startTimeInThisDay.set(startTime.toMillis(true) + aDayInMillis);
            if (!now.before(startTimeInThisDay)) {
                result = true;
            }
        } else {
            /**普通情况(比如5:00-10:00)*/
            result = !now.before(startTime) && !now.after(endTime); // startTime <= now <= endTime
        }
        return result;
    }
}